package com.peng.leetcode.tree;

/**
 * SumRootToLeaf
 *
 * @author: lupeng6
 * @create: 2021/2/23 14:53
 */
public class SumRootToLeaf {

    public static void main(String[] args) {
        TreeNode treeNode = TreeMain.array2tree(new Integer[]{1, 0, 1, 0, 1, 0, 1});
        System.out.println(new SumRootToLeaf().sumRootToLeaf(treeNode));
    }

    private int answer = 0;

    public int sumRootToLeaf(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root, "");
        return answer;
    }

    private void dfs(TreeNode node, String pathValue) {
        if (node == null) {
            return;
        }
        pathValue = pathValue + node.val;
        if (node.left == null && node.right == null) {
            answer += Integer.parseInt(pathValue, 2);
        }
        dfs(node.left, pathValue);
        dfs(node.right, pathValue);
    }

}
